package com.penngo.gui.dfdiff;

import cn.hutool.core.io.FileUtil;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONUtil;
import com.penngo.gui.dfdiff.utils.*;
import com.penngo.gui.dfdiff.view.*;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class DFMain extends JFrame {
    private static Logger log = LogUtils.getLogger(DFMain.class);
    private JFileChooser fileChooser = null;
    private JFileChooser folderChooser = null;
    private static final List<File> fileArgs = new ArrayList<>(2);
    public static TransferHandler handler = null;
    public static ProjectTable projectTable;
    public static DesktopPane desktopPane;
    public static LimitList historyList = new LimitList();

    // 使用graalvm编译为原生应用时，需要设置java.home为当前目录
    static {
//        System.setProperty("java.home", ".");
//        System.setProperty("java.home", ToolUtil.getRunPath()); // windows
    }

    public DFMain(){
        setTitle(AppInfo.Name);
        setIconImage(ImgUtil.IMAGE_LOGO_APP.getImage());

        setJMenuBar(new MainMenu());

        projectTable = new ProjectTable();
        desktopPane = new DesktopPane();
//        projectTable.setDesktopPane(desktopPane);
        JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(projectTable),
                desktopPane);
        sp.setDividerLocation(150);
        getContentPane().add(sp);

        setSize((int)(ScreenUtil.getScreenWidth() * 0.8), (int)(ScreenUtil.getScreenHeight() * 0.8));

        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        handler = new FileTransferHandler();
        setTransferHandler(handler);

        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                log.info("windowClosing=====");
                //historyList.saveHistory();
            }
        });

        initOpenFile();
    }

    private void initOpenFile(){
        new Thread(()->{
            historyList.loadHistory();
            if(fileArgs.size() == 1){
                File file = fileArgs.get(0);

                if(file.isFile()){
                    ProjectNode node = new ProjectNode(file.getName(), file, null, ProjectNode.ProjectType.FILE);
                    openFile(node);
                }
                else{
                    ProjectNode node = new ProjectNode(file.getName(), file, null, ProjectNode.ProjectType.FOLDER);
                    openFolder(node);
                }
            }
            // 打开目录比较
            else if(fileArgs.size() == 2){
                File leftFile = fileArgs.get(0);
                File rightFile = fileArgs.get(1);
                if(leftFile.isFile() && rightFile.isFile()){
                    ProjectNode node = new ProjectNode(leftFile.getName() + "<->" + rightFile.getName(), leftFile, rightFile, ProjectNode.ProjectType.FILE_DIFF);
                    openDiffFile(node);
                }
                else if(leftFile.isDirectory() && rightFile.isDirectory()){
                    ProjectNode node = new ProjectNode(leftFile.getName() + "<->" + rightFile.getName(), leftFile, rightFile, ProjectNode.ProjectType.FOLDER_DIFF);
                    openDiffFolder(node);
                }
            }
        }).start();
    }

    class FileTransferHandler extends TransferHandler{
        public boolean canImport(TransferSupport support) {
            if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) ||
                    support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return true;
            }
            return false;
        }

        public boolean importData(TransferSupport support) {
            Transferable t = support.getTransferable();

            try{
                if(support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) == true){
                    List<File> l = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                    for (File f : l) {
                        if(f.isFile()){
                            ProjectNode node = new ProjectNode(f.getName(), f.getAbsoluteFile(), null, ProjectNode.ProjectType.FILE);
                            DFMain.this.openFile(node);
                        }
                        else if(f.isDirectory()){
                            ProjectNode node = new ProjectNode(f.getName(), f.getAbsoluteFile(), null, ProjectNode.ProjectType.FOLDER);
                            DFMain.this.openFolder(node);
                        }
                    }
                }
                else if(support.isDataFlavorSupported(DataFlavor.stringFlavor) == true){
                    if(support.getComponent() instanceof RSyntaxTextArea textArea){
                        String text = (String)t.getTransferData(DataFlavor.stringFlavor);
                        int p = textArea.getCaretPosition();
                        textArea.insert(text, p);
                    }
                }
            }
            catch(Exception e){
//                e.printStackTrace();
                log.log(Level.SEVERE, "FileTransferHandler error", e);
                return false;
            }
            return true;
        }
    }

    class MainMenu extends JMenuBar {
        public MainMenu() {
            JPopupMenu.setDefaultLightWeightPopupEnabled(false);//关键一行。
            /////////////////////// 文件菜单
            add(new FileMenu());
            /////////////////////// 编辑菜单
            add(new EditMenu());
            /////////////////////// 对比菜单
            add(new ToolMenu());
            /////////////////////// 窗口菜单
            add(new WindowMenu());
            /////////////////////// 帮助菜单
            add(new HelpMenu());
            ////

        }

        class FileMenu extends JMenu {
            private final String str_newfile = "新建文件";
            private final String str_openfile = "打开文件";
            private final String str_openFolder = "打开文件夹";
            private final String str_savefile = "保存文件";
            private final String str_saveAsfile = "另存文件";
            private final String str_exit = "退出";

            public FileMenu() {
                super("文件");
                AbstractAction action = new FileAction();
                JMenuItem newFileItem = new JMenuItem(str_newfile);
                newFileItem.addActionListener(action);
                add(newFileItem);

                JMenuItem openFileItem = new JMenuItem(str_openfile);
                openFileItem.setIcon(ImgUtil.IMAGE_FILE);
                openFileItem.addActionListener(action);
                add(openFileItem);

                JMenuItem openFolderItem = new JMenuItem(str_openFolder);
                openFolderItem.setIcon(ImgUtil.IMAGE_FOLDER);
                openFolderItem.addActionListener(action);
                add(openFolderItem);

                // 最近打开的文件/文件夹
                JMenu openLastMenu = new FileLastMenu();
                add(openLastMenu);



                JMenuItem saveFileItem = new JMenuItem(str_savefile);
                saveFileItem.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
                        java.awt.Event.CTRL_MASK));
                saveFileItem.addActionListener(action);
                add(saveFileItem);

                JMenuItem saveAsFileItem = new JMenuItem(str_saveAsfile);
                saveAsFileItem.addActionListener(action);
                add(saveAsFileItem);

                addSeparator();

                JMenuItem exitItem = new JMenuItem(str_exit);
                exitItem.addActionListener(action);
                add(exitItem);
            }

            class FileAction extends AbstractAction {

                @Override
                public void actionPerformed(ActionEvent event) {
                    String command = event.getActionCommand();
                    switch (command) {
                        case str_newfile:
                            newFile(null);
                            break;
                        case str_openfile:
                            openFile(null);
                            break;
                        case str_openFolder:
                            openFolder(null);
                            break;
                        case str_savefile:
                            saveFile(false);
                            break;
                        case str_saveAsfile:
                            saveFile(true);
                            break;
                        case str_exit:
                            System.exit(0);
                            break;
                    }
                }
            }
        }

        class FileLastMenu extends JMenu{
            private final static String str_lastFileFolder = "最近打开的文件/文件夹";

            public FileLastMenu(){
                super(str_lastFileFolder);
                addMouseListener(new FileMouseAdapter());
            }

            class FileMouseAdapter extends MouseAdapter {

                private FileLastItemAction itemAction = new FileLastItemAction();

                public void mouseEntered(MouseEvent e) {
                    if(FileLastMenu.this.isPopupMenuVisible() == false){
                        // 读取打开过的文件/文件夹
                        if(historyList.size() > 0){
                            FileLastMenu.this.removeAll();
                            historyList.forEach(node->{
                                JMenuItem item = new JMenuItem(((DataNode)node).getTitle());
                                item.setName(node.getUuid());
                                item.addActionListener(itemAction);
                                FileLastMenu.this.add(item);
                            });
                        }
                    }
                }
            }
            class FileLastItemAction extends AbstractAction {
                @Override
                public void actionPerformed(ActionEvent event) {
                    String itemcode = ((JMenuItem)event.getSource()).getName();
                    if(historyList.size() > 0){
                        for(int i = 0; i < historyList.size(); i++){
                            ProjectNode nodeTemp = historyList.get(i);
                            if(nodeTemp != null && itemcode.equals(nodeTemp.getUuid())){
                                ProjectNode node = nodeTemp.clone();// new ProjectNode(nodeTemp.getTitle(), nodeTemp.getPathLeft(), nodeTemp.getPathRight(), nodeTemp.getType());
                                switch (node.getType()){
                                    case FILE -> {
                                        if(node != null && node.getPathLeft().exists()){
                                            openFile(node);
                                        }
                                    }
                                    case FOLDER -> {
                                        openFolder(node);
                                    }
                                    case FILE_DIFF -> {
                                        openDiffFile(node);
                                    }
                                    case FOLDER_DIFF -> {
                                        openDiffFolder(node);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }

        class EditMenu extends JMenu{
            private final String str_undo = "撤消";
            private final String str_redo = "恢复";
            private final String str_copy = "复制";
            private final String str_paste = "粘贴";
            private final String str_cut = "剪切";
            private final String str_find = "查找...";
            private final String str_font = "字体";
            private final String str_line = "换行";

            private final int shortcutKey = ToolUtil.isMac() == true ? KeyEvent.META_DOWN_MASK : KeyEvent.CTRL_DOWN_MASK;
            public EditMenu(){
                super("编辑");
                AbstractAction action = new EditAction();
                JMenuItem undoItem = new JMenuItem(str_undo);
                undoItem.addActionListener(action);
//                undoItem.setActionCommand("Undo");
                undoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, shortcutKey));
                add(undoItem);

                JMenuItem redoItem = new JMenuItem(str_redo);
                redoItem.addActionListener(action);
//                redoItem.setActionCommand("Redo");
                redoItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, shortcutKey));
                add(redoItem);

                addSeparator();
                JMenuItem copyItem = new JMenuItem(str_copy);
                copyItem.addActionListener(action);
//                copyItem.setActionCommand("Copy");
                copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, shortcutKey));
                add(copyItem);

                JMenuItem pasteItem = new JMenuItem(str_paste);
                pasteItem.addActionListener(action);
//                pasteItem.setActionCommand("Paste");
                pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, shortcutKey));
                add(pasteItem);

                JMenuItem cutItem = new JMenuItem(str_cut);
                cutItem.addActionListener(action);
//                cutItem.setActionCommand("Cut");
                cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, shortcutKey));
                add(cutItem);

                JMenuItem findItem = new JMenuItem(str_find);
                findItem.addActionListener(action);
//                findItem.setActionCommand("Find...");
                findItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, shortcutKey));
                add(findItem);

                addSeparator();

                JMenuItem fontItem = new JMenuItem(str_font);
                fontItem.addActionListener(action);
                add(fontItem);

                JCheckBoxMenuItem lineItem = new JCheckBoxMenuItem(str_line);
                lineItem.setState(Config.isIsLineWrap());
                lineItem.addActionListener(action);
                add(lineItem);

            }

            class EditAction extends AbstractAction {
                @Override
                public void actionPerformed(ActionEvent event) {
                    DesktopFrame frame = (DesktopFrame)DFMain.desktopPane.getSelectedFrame();
                    String command = event.getActionCommand();
                    switch (command) {
                        case str_undo:
                            frame.undo();
                            break;
                        case str_redo:
                            frame.redo();
                            break;
                        case str_copy:
                            frame.copy();
                            break;
                        case str_paste:
                            frame.paste();
                            break;
                        case str_cut:
                            frame.cut();
                            break;
                        case str_find:
                            frame.find();
                            break;
                        case str_font:
                            new FontDialog();
                            break;
                        case str_line:
                            lineWrap();
                            break;
                    }
                }
            }
        }

        class ToolMenu extends JMenu {
            private final String str_difffold = "文件夹对比";
            private final String str_difffile = "文件对比";
            private final String str_json = "json格式化";

            public ToolMenu() {
                super("工具");
                AbstractAction action = new ToolAction();
                JMenuItem diffFoldItem = new JMenuItem(str_difffold);
                diffFoldItem.setIcon(ImgUtil.IMAGE_FOLDER_DIFF);
                diffFoldItem.addActionListener(action);
                add(diffFoldItem);
                JMenuItem diffFileItem = new JMenuItem(str_difffile);
                diffFileItem.setIcon(ImgUtil.IMAGE_FILE_DIFF);
                diffFileItem.addActionListener(action);
                add(diffFileItem);

                addSeparator();

                JMenuItem jsonItem = new JMenuItem(str_json);
                jsonItem.addActionListener(action);
                add(jsonItem);


            }

            class ToolAction extends AbstractAction {

                @Override
                public void actionPerformed(ActionEvent event) {
                    String command = event.getActionCommand();
                    switch (command) {
                        case str_difffold:
                            openDiffFolder(null);
                            break;
                        case str_difffile:
                            openDiffFile(null);
                            break;
                        case str_json:
                            itemJsonFormat();
                            break;

                    }
                }
            }
        }

        class WindowMenu extends JMenu{
            private final String str_window_cascad = "窗口层叠";
            private final String str_window_minimize = "窗口最小化";

            public WindowMenu() {
                super("窗口");
                AbstractAction action = new WindowAction();
                JMenuItem windowCascadItem = new JMenuItem(str_window_cascad);
                windowCascadItem.addActionListener(action);
                add(windowCascadItem);

                JMenuItem windowMinimizeItem = new JMenuItem(str_window_minimize);
                windowMinimizeItem.addActionListener(action);
                add(windowMinimizeItem);
            }
            class WindowAction extends AbstractAction {

                @Override
                public void actionPerformed(ActionEvent event) {
                    String command = event.getActionCommand();
                    switch (command) {
                        case str_window_cascad:
                            //itemJsonFormat();
                            menuWindowCascad();
                            break;
                        case str_window_minimize:
                            menuWindowMinimize();
                            //itemJsonFormat();
                            break;
                    }
                }
            }
        }

        class HelpMenu extends JMenu {
            private final String str_about = "关于";
            public HelpMenu() {
                super("帮助");
                AbstractAction action = new HelpAction();
//                add(helpMenu);
                JMenuItem aboutItem = new JMenuItem(str_about);
                aboutItem.addActionListener(action);
                add(aboutItem);
                //this.setJMenuBar(bar);
            }

            class HelpAction extends AbstractAction {
                @Override
                public void actionPerformed(ActionEvent event) {
                    String command = event.getActionCommand();
                    switch (command) {
                        case str_about:
                            AboutDialog.Show();
                            break;
                    }
                }
            }
        }
    }

        private void initToolBar(){

        JToolBar toolBar = new JToolBar("工具栏");
        Insets zeroInset = new Insets(2, 0, 2, 2);

        JButton newButton = new JButton("文件夹");
        newButton.setHorizontalTextPosition(SwingConstants.CENTER);
        newButton.setVerticalTextPosition(SwingConstants.BOTTOM);
        ImageIcon folderIcon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(
                DFMain.class.getResource("/images/folder.png")));
        folderIcon.setImage(folderIcon.getImage().getScaledInstance(24,24, Image.SCALE_DEFAULT));
        newButton.setIcon(folderIcon);
        newButton.setMargin(zeroInset);
        newButton.setToolTipText("文件夹对比");

        newButton.addActionListener(e-> openDiffFolder(null));

        JButton fileButton = new JButton(" 文件 ");
        fileButton.setHorizontalTextPosition(SwingConstants.CENTER);
        fileButton.setVerticalTextPosition(SwingConstants.BOTTOM);
        ImageIcon fileIcon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(
                DFMain.class.getResource("/images/file.png")));
        fileIcon.setImage(fileIcon.getImage().getScaledInstance(24,24, Image.SCALE_DEFAULT));
        fileButton.setIcon(fileIcon);
        fileButton.setMargin(zeroInset);
        fileButton.setToolTipText("文件对比");
        fileButton.addActionListener(e->{
            File leftFile = null;
            File rightFile = null;

        });

        toolBar.add(newButton);
        toolBar.add(fileButton);

        toolBar.setRollover(true);
        getContentPane().add(toolBar, BorderLayout.NORTH);

    }
    private void newFile(ProjectNode node){
        if(node == null){
            node = new ProjectNode("未命名文件", null,null, ProjectNode.ProjectType.FILE);
            DFMain.historyList.addFirst(node);
        }
//        ProjectNode node = new ProjectNode("未命名文件", null,null, ProjectNode.ProjectType.FILE);
        projectTable.addNode(node);
        DesktopFrame frame = new DesktopFrameEditor(node);
        desktopPane.add(frame);
        frame.setVisible(true);
    }
    private void openFile(ProjectNode node){
        if(fileChooser == null){
            initFileChooser();
        }
        if(node == null){
            int returnVal = fileChooser.showOpenDialog(null);
            if(returnVal ==JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                log.info("openFile======" + file.getAbsolutePath());
                node = new ProjectNode(file.getName(), file,null, ProjectNode.ProjectType.FILE);
                DFMain.historyList.addFirst(node);
            }
        }
        if(node != null && node.getPathLeft().exists()){
            projectTable.addNode(node);
            DesktopFrame frame = new DesktopFrameEditor(node);
            desktopPane.add(frame);
            frame.setVisible(true);
            historyList.saveHistory();
        }
    }

    public void openFolder(ProjectNode node){
        if(node == null){
            if(folderChooser == null){
                folderChooser = new JFileChooser(".");
                folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            }

            int result = folderChooser.showOpenDialog(null);
            if(result == JFileChooser.APPROVE_OPTION){
                File selectFile = folderChooser.getSelectedFile();
                node = new ProjectNode(selectFile.getName(), selectFile,null, ProjectNode.ProjectType.FOLDER);
                DFMain.historyList.addFirst(node);
            }
        }
        if(node != null){
            File[] files = node.getPathLeft().listFiles();
            if(files != null && files.length > 0){
                for(File file:files){
                    ProjectNode child = new ProjectNode(file.getName(), file,null, ProjectNode.ProjectType.FOLDER);
                    node.addChildren(child);
                }
            }
            projectTable.addNode(node);
            historyList.saveHistory();
        }
    }



    private void initFileChooser(){
        //创建文件选择器
        fileChooser = new JFileChooser();
        //后缀名过滤器
        Map<String, List<String>> map = ToolUtil.getFileExtension();
        map.forEach((style, list)->{
            //style = style.substring(style.indexOf("/") + 1);
            String str = list.stream().map(s-> "*." + s).collect(Collectors.joining(";"));
            FileNameExtensionFilter f = new FileNameExtensionFilter(style + " (" + str + ")", list.toArray(String[]::new));
//            fileChooser.setFileFilter(f);
            fileChooser.addChoosableFileFilter(f);
        });
    }
    private void saveFile(boolean isSaveAs){
        DesktopFrame frame = (DesktopFrame)desktopPane.getSelectedFrame();
        if(frame instanceof DesktopFrameEditor frameEditor){
            if(fileChooser == null){
                initFileChooser();
            }
            ProjectNode node = frameEditor.getProjectNode();
            File curFile = node.getPathLeft();
            boolean isCreate = false;
            if(curFile == null || isSaveAs == true){
                int returnVal = fileChooser.showSaveDialog(null);
                if(returnVal ==JFileChooser.APPROVE_OPTION) {
                    File f = fileChooser.getSelectedFile();
                    //字节输出流
                    try {
                        String fname = f.getName();//从文件名输入框中获取文件名
                        FileFilter fileFilter = fileChooser.getFileFilter();
                        String fullname = new StringBuffer().append(fileChooser.getCurrentDirectory())
                                .append("/").append(fname).toString();
                        if(fileFilter instanceof FileNameExtensionFilter){
                            String[] ext = ((FileNameExtensionFilter)fileFilter).getExtensions();
                            fullname = new StringBuffer().append(fileChooser.getCurrentDirectory())
                                    .append("/").append(fname).append(".").append(ext[0]).toString();
                        }
                        //创建文件
                        curFile = new File(fullname);
                        node.setTitle(curFile.getName());
                        node.setPathLeft(curFile);
                        isCreate = true;
                        frameEditor.setTitle(curFile.getName());
                        projectTable.updateUI();
                    } catch (Exception e1) {
                        log.log(Level.SEVERE, "IO异常=====", e1);
                    }
                }

            }

            FileUtil.writeString(frameEditor.getEditor().getText(), curFile, "UTF-8");
            if(isCreate == true){
                historyList.addFirst(node);
                historyList.saveHistory();
            }
        }
    }

    private void openDiffFolder(ProjectNode node){
        if(node == null){
            node = new ProjectNode("文件夹对比", null,null, ProjectNode.ProjectType.FOLDER_DIFF);
            DFMain.historyList.addFirst(node);
        }

        projectTable.addNode(node);

        DesktopFrame frame = new DesktopFrameFolderDiff(node);
        desktopPane.add(frame);
        frame.setVisible(true);
    }

    private void openDiffFile(ProjectNode node){
        //new FileDiffDialog(null, null);
        if(node == null){
            node = new ProjectNode("文件对比", null,null, ProjectNode.ProjectType.FILE_DIFF);
            DFMain.historyList.addFirst(node);
        }
        projectTable.addNode(node);
        DesktopFrame frame = new DesktopFrameFileDiff(node);
        desktopPane.add(frame);
        frame.setVisible(true);
    }
    private void lineWrap(){
        boolean b = !Config.isIsLineWrap();
        Config.setIsLineWrap(b);
        JInternalFrame[] frames = desktopPane.getAllFrames();
        try{
            for(JInternalFrame frame:frames){
                if(frame instanceof DesktopFrameEditor desktopFrame){
                    desktopFrame.setLineWrap(b);
                }
            }
        }
        catch(Exception e){
            log.log(Level.SEVERE, "===WindowCascad error", e.getMessage());
        }
    }
    private void itemJsonFormat(){
        DesktopFrame frame = (DesktopFrame)desktopPane.getSelectedFrame();
        if(frame instanceof DesktopFrameEditor frameEditor){
            String text = frameEditor.getEditor().getTextArea().getText();
            String jsonPretty = JSONUtil.toJsonPrettyStr(text);
            frameEditor.getEditor().getTextArea().setText(jsonPretty);

        }
    }

    private void menuWindowCascad(){
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if(frames != null && frames.length > 0){
            DesktopFrame.resetOpenFrameCount();
        }
        try{
            for(JInternalFrame frame:frames){
                if(frame instanceof DesktopFrame desktopFrame){
                    desktopFrame.setIcon(false);
                    desktopFrame.resetLocation();
                    desktopFrame.setFrameSelected(true);
                }
            }
        }
        catch(Exception e){
            log.log(Level.SEVERE, "===WindowCascad error", e.getMessage());
        }

    }
    private void menuWindowMinimize(){
        JInternalFrame[] frames = desktopPane.getAllFrames();
        try{
            for(JInternalFrame frame:frames){
                frame.setIcon(true);
            }
        }
        catch(Exception e){
            log.log(Level.SEVERE, "===WindowMinimize error", e.getMessage());
        }
    }


    /**
     * ./DFDiff -Djava.home=. -Dsun.awt.fontconfig=./fontconfig.properties
     * @param args
     */
    public static void main(String[] args) {
//        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
//            log.info("保存打开历史=====");
//        }));
        try {
            if(args.length > 0){
                Arrays.asList(args).forEach(arg->{
                    log.info("args======" + arg);
                    File file = new File(arg);
                    if(file.exists() && fileArgs.size() < 2){
                        fileArgs.add(new File(arg));
                    }
                });

            }
            System.setProperty("file.encoding","UTF-8");
            System.setProperty("sun.java2d.dpiaware", "true");

//            System.setProperty("sun.java2d.uiScale", "1");

            // 抗锯齿
//            System.setProperty("awt.useSystemAAFontSettings","on");
//            System.setProperty("swing.aatext", "true");

            ToolUtil.initLookAndFeel();

//            FontUtil.test();
            FontUtil.initGobalFont();

            SwingUtilities.invokeLater(() ->  {
                DFMain dfMain = new DFMain();
                dfMain.setVisible(true);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}